package com.yanyeori.framework.redis.listener;

import com.yanyeori.framework.redis.disruptor.producer.RedisPushEventProducer;
import com.yanyeori.framework.redis.model.PushMessage;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * redis监听消息处理类
 *
 * @author chenkuan 2020/08/18
 */
public class MessageListenerDelegate implements MessageListener {
    private RedisSerializer<?> serializer;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        RedisPushEventProducer producer = RedisPushEventProducer.getInstance();
        producer.send((PushMessage) extractMessage(message));
    }

    private Object extractMessage(Message message) {
        if (serializer != null) {
            return serializer.deserialize(message.getBody());
        }
        return message.getBody();
    }

    public void setSerializer(RedisSerializer<?> serializer) {
        this.serializer = serializer;
    }
}
